import hashlib

import torque.settings as settings
import time
import simplejson as json
import torque.api.logging as tal
import torque.api.errors as tae
import torque.api.torrents as tat
from torque.api.nameparser import NameParser as tatv

from torque.torrent.models import Torrent
from django.http import HttpResponse

def _handleFile(f,location=settings.TORQUE['torrent_path'],random=False):
    if random:
        name = hashlib.sha1(str(time.clock())+':'+f.name).hexdigest()+'.torrent'
    else:
        name = f.name
    dest = location + name
    try:
        file = open(dest, 'wb+')
    except:
        raise IOError('Could not access '+dest)
    else:
        for chunk in f.chunks():
            file.write(chunk)
        file.close()
    
    return dest
    
def upload(request):
    return HttpResponse('<form method="POST" action="/torrents/details/" enctype="multipart/form-data"><input type="file" name="file" /><input type="submit" /></form>')

def details(request):
    storeLocation = settings.TORQUE["torrent_path"] + 'tmp/';
    if 'file-path' in request.FILES:
        path = _handleFile(request.FILES['file-path'],storeLocation,True)
        outputObj = {'success':True,'msg':tat.getDetails(path)}
        
        return HttpResponse(json.dumps(outputObj))
        
    return HttpResponse(json.dumps({'success':False,'msg':'You did not upload a file!'}))   

def check(request):
    torrentPath = request.REQUEST.get('path',None)
    if torrentPath == None:
        return HttpResponse(tae.errors['missing_parameter'] % 'path')
        
    torrentPath = settings.TORQUE['torrent_path'] + torrentPath
    
    details = tat.getDetails(torrentPath)
    if details == None:
        return HttpResponse(tae.errors['invalid_parameters'] % 'path')
        
    try:
        Torrent.objects.get(hash = details['hash'], status='A')
    except Torrent.DoesNotExist: # THIS IS A GOOD THING
        tvDupeMatches = []
        newName = tatv(details['name'])
        torrents = Torrent.objects.filter(status='A')
        for torrent in torrents:
            existingName = tatv(torrent.name)
            if newName.match(existingName):
                tvDupeMatches.append(torrent.name)
        
        if(len(tvDupeMatches) < 1):
            simpleName = tat.generateSimpleName(details['name'])
            try:
                torrentMatches = Torrent.objects.filter(simplename = simpleName, status='A')
            except Torrent.DoesNotExist:
                matches = []
            else:
                matches = []
                for torrent in torrentMatches:
                    matches.append(torrent.name)
        else:
            matches = []
        
        combinedMatches = list(tvDupeMatches + matches);
        strMatches = []
        if(len(combinedMatches) > 0):
            for torrent in combinedMatches:
                strMatches.append(torrent)
        
        return HttpResponse(json.dumps({'exists':0,'matchCount':len(strMatches),'matches':strMatches}))
    else:
        return HttpResponse(tae.errors['torrent_exists'])
